from python_quant.common.sql.SQLAlchemy.SQLAlchemyHelper import Session


class SqlalchemyORM:
    def init(self):
        self.session = Session()

    def add(self, obj):

        try:
            self.session.add(obj)
            self.session.commit()
            return True
        except Exception as e:
            print(f"add error:{obj}-{e}")
            self.session.rollback()
            return False


def update(self, obj):
    try:
        self.session.commit()
        return True
    except Exception as e:
        print(f"update error:{obj}-{e}")
        self.session.rollback()
        return False


def delete(self, obj):
    try:
        self.session.delete(obj)
        self.session.commit()
        return True
    except Exception as e:
        print(f"delete error:{obj}-{e}")
        self.session.rollback()
        return False


def query_all(self, cls):
    try:
        return self.session.query(cls).all()
    except Exception as e:
        print(f"query_all error:{cls}-{e}")
        return []


def query_filter(self, cls, kwargs):
    try:
        return self.session.query(cls).filter_by(kwargs).all()
    except Exception as e:
        print(f"query_filter error:{cls}-{kwargs}-{e}")
        return []


def close(self):
    self.session.close()
